package com.group.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.base.view.GeneralResult;
import com.group.model.User;
import com.group.model.UserTicker;
import com.group.util.NoteException;
import com.group.util.WeiXinUtils;

/**
 * 支付提现相关接口
 * 
 * @author zhaolei
 *
 */
@Controller
public class PaymentController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(PaymentController.class);

	private String baseurl = "https://open.fingo.com/";

	private String client_id = "879b23b7c2154d9bb9203e9a750159ff";

	private String client_secret = "6609605662d69f2335a22a2716d4bccb297dd959";

	private String token = null;

	// 过期时间
	private Long expire = null;

	private String bank2Tel = "8613575499466";

	private double czrMoney = 0.3;

	@GetMapping("/payment/oauth/token")
	@ResponseBody
	public GeneralResult<String> testToken(HttpServletResponse response) throws Exception {

		return new GeneralResult<String>().setValue(getWalletToken() + "_________" + expire);
	}

	/**
	 * 提现
	 * @param amount
	 * @param response
	 * @param request
	 * @throws Exception
	 */
	@GetMapping("/payment/cash")
	@ResponseBody
	public synchronized void cash(Double amount, HttpServletResponse response, HttpServletRequest request) throws Exception {
		if (amount <= 35)
			throw new NoteException("提现数额必须大于35");

		User user = getUser(request);
		if (user == null)
			throw new NoteException("user 不存在");
		if (user.getTel() == null)
			throw new NoteException("手机号 不存在");
		if (user.getQyOpenid() == null || "null".equals(user.getQyOpenid()))
			throw new NoteException("数据错误 用户千言openid'为空,请重新进入提现页面, userId=" + user.getId());

		synchronized (user.getId()) {
			Long userId = user.getId();
			UserTicker ut = tickerService.getUserTicker(userId, "czr");
			if (ut == null || ut.getNum() < amount) {
				throw new NoteException("余额不足");
			}

			if (ut.getCashing() != 0) {
				throw new NoteException("当前有一笔提现中的交易,不能发起新的提现");

			}

			String billNo = getBillNum();

			// 调用钱包提现
			String url = baseurl + "v1/transaction/commit";
			String para = "coin_name=CZR&sender_mobile=8617606718182&access_token=" + getWalletToken() + "&from_bank_mobile=8617606718182&to_bank_mobile=8613575499466" + "&transaction_id=" + billNo + "&amount="
					+ (amount) + "&receiver_mobile=86" + user.getTel() + "&receiver_name=" + user.getName();

			String result = WeiXinUtils.formPost(url, para);
			logger.info("提现结果为: " + result);
			JSONObject obj = JSONObject.parseObject(result);
			if (obj.getBooleanValue("success") == false) {
				throw new NoteException("提现失败 result = " + result);
			}

			tickerService.addTicker(userId, "czr", -amount, "提现", null, "进行中", billNo, 35d, null);
			response.getWriter().write(result);
		}

	}

	/**
	 * 获取钱包token
	 * 
	 * @return
	 */
	public String getWalletToken() {
		if (token != null && (System.currentTimeMillis() / 1000 < expire)) {
			return token;
		} else {
			try {
				String result = WeiXinUtils.formPost(baseurl + "oauth/token", "client_id=" + client_id + "&client_secret=" + client_secret + "&grant_type=client_credentials&scope=trust");
				JSONObject obj = JSONObject.parseObject(result);
				token = obj.getString("access_token");
				expire = System.currentTimeMillis() / 1000 + obj.getIntValue("expires_in");

			} catch (Exception e) {
			}

			return token;
		}

	}

}
